package cn.skywalks.common.utils.http;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;

/**
 * Created by lpeng on 2017/7/25.
 */
public class HttpUtil {

    private static Logger logger = Logger.getLogger(HttpUtil.class);

    private static String url = "http://www.baidu.com";

    public static void main(String[] args) throws IOException {
        Map<String, Object> map = new HashMap();
        map.put("aldtype", "16047#en/zh/medium");
        String s = HttpUtil.doGet("http://localhost:8082/member/get", map);
        System.out.println(s);

    }

    public static String doGet(String url, Map<String, Object> params){
        CloseableHttpResponse response = null;
        BufferedReader reader = null;
        String retStr = null;
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            UrlEncodedFormEntity entity = (UrlEncodedFormEntity) HttpUtil.params2Entity(params);
            String paramsStr = EntityUtils.toString(entity);
            logger.info(URLDecoder.decode(paramsStr, "UTF-8"));
            HttpGet get = new HttpGet(url + "?" + paramsStr);
            response = httpClient.execute(get);
            if (null != response && (response.getStatusLine().getStatusCode() == 200)) {
                reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            }
            retStr = HttpUtil.bufferedReader2String(reader);
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            if (reader != null){
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (response != null ){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return retStr;
    }

    /**
     * 发送post请求
     * @param url url
     * @param params 请求参数
     * @return
     * @author lupeng6
     */
    public static String doPost(String url, Map<String, Object> params){
        CloseableHttpClient httpClient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(2000).setSocketTimeout(2000).build();
        HttpPost post = new HttpPost(url);
        post.setConfig(requestConfig);
        CloseableHttpResponse response = null;
        BufferedReader reader = null;
        String retStr = null;
        try {
            HttpEntity entity = HttpUtil.params2Entity(params);
            post.setEntity(entity);
            response = httpClient.execute(post);
            if (response != null && response.getStatusLine().getStatusCode() == 200){
                reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            }
            retStr = HttpUtil.bufferedReader2String(reader);
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            if (reader != null){
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return retStr;
    }

    static List<NameValuePair> params2List(Map<String, Object> params){
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        if (params != null){
            Iterator<Map.Entry<String, Object>> iterator = params.entrySet().iterator();
            while (iterator.hasNext()){
                Map.Entry<String, Object> next = iterator.next();
                pairs.add(new BasicNameValuePair(next.getKey(), (String) next.getValue()));
            }
        }
        return pairs;
    }

    static HttpEntity params2Entity(Map<String, Object> params) throws UnsupportedEncodingException {
        HttpEntity entity = null;
        List<NameValuePair> pairs = HttpUtil.params2List(params);
        if (pairs != null){
            entity = new UrlEncodedFormEntity(pairs, "UTF-8");
        }
        return entity;
    }

    static String bufferedReader2String(BufferedReader reader) throws IOException {
        String ret = null;
        if (reader != null){
            StringBuffer buffer = new StringBuffer();
            String temp = null;
            while ((temp = reader.readLine()) != null){
                buffer.append(temp);
            }
            ret = buffer.toString();
        }
        return ret;
    }

}
